package org.uninova.mobis.gtfs.parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;

import org.uninova.mobis.gtfs.db.GTFSDatabaseInteraction;
import org.uninova.mobis.pojos.Agency;
import org.uninova.mobis.pojos.Calendar;
import org.uninova.mobis.pojos.CalendarDate;
import org.uninova.mobis.pojos.FeedInfo;
import org.uninova.mobis.pojos.Route;
import org.uninova.mobis.pojos.Stop;
import org.uninova.mobis.pojos.StopTime;
import org.uninova.mobis.pojos.Transfer;
import org.uninova.mobis.pojos.Trip;
import org.uninova.mobis.utils.DBUtilsImpl;

public class GTFSParser {
	
	public GTFSParser() {} 

	public int parseAgency(String filePath) {
		try {  
			File file = new File (filePath + "agency.txt") ;
			if (file.exists()) {
				FileReader fr = new FileReader(file) ;
				
				DBUtilsImpl dbUtils = new DBUtilsImpl() ;
				//Connection conn = dbUtils.startConnection("jdbc:sqlserver://10.172.66.247:1433;databaseName=MobiS_DB", "paf", "grisgris123") ;
				Connection conn = dbUtils.startConnection("jdbc:mysql://10.172.66.247:3306", "root", "grisgris123") ;
				
				GTFSDatabaseInteraction dbInt = new GTFSDatabaseInteraction() ;
				
				BufferedReader br = new BufferedReader(fr);
				String currentRecord;
				String delimiter = "," ;
				boolean flag = true;
				int result = -1, agencyId = -1, agencyName = -1, agencyUrl = -1, agencyTimezone = -1, agencyLang = -1, agencyPhone = -1, agencyFareUrl = -1 ;
				Agency agency = null ;
				String[] fields ;
				String field ;
				DateFormat fmt, other ;
				java.util.Date date ;
				while((currentRecord = br.readLine()) != null) {
					fields = currentRecord.split(delimiter) ;
					if (flag) {
						for (int i = 0; i < fields.length; i++) {
							field = fields[i] ;
							if (field.equals("agency_id")) 
								agencyId = i ;
							if (field.equals("agency_name"))
								agencyName = i ;
							if (field.equals("agency_url"))
								agencyUrl = i ;
							if (field.equals("agency_timezone"))
								agencyTimezone = i ;
							if (field.equals("agency_lang"))
								agencyLang = i ;
							if (field.equals("agency_phone"))
								agencyPhone = i ;
							if (field.equals("agency_fare_url"))
								agencyFareUrl = i ;
							flag = false ;
						}
					}
					else {
						agency = new Agency() ;
						for (int i = 0; i < fields.length; i++) {
							if (agencyId == i) {
								
								agency.setAgencyId(Integer.parseInt(fields[i].replace(" ", ""))) ;
							}
							else if (agencyName == i)
								agency.setAgencyName(fields[i].replace("'", "''")) ;
							else if (agencyUrl == i) 
								agency.setAgencyUrl(fields[i].replace("'", "''")) ;
							else if (agencyLang == i) 
								agency.setAgencyLang(fields[i].replace("'", "''")) ;
							else if (agencyTimezone == i) 
								agency.setAgencyTimezone(fields[i].replace("'", "''")) ;
							else if (agencyPhone == i) 
								agency.setAgencyPhone(fields[i].replace("'", "''")) ;
							else if (agencyFareUrl == i) 
								agency.setAgencyFareUrl(fields[i].replace("'", "''")) ;
						}
						
						if (agencyPhone != -1 && agencyFareUrl != -1)
							result = dbInt.insertAllFieldsAgency(conn, agency) ;
						else 
							result = dbInt.insertRequiredFieldsAgency(conn, agency) ;
					}
				}
				conn.close() ;
				fr.close() ;
				br.close();
				return result ;
			}
			else return 1 ;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1 ;
	}
	
	public int parseRoutes(String filePath) {
		try {  
			File file = new File (filePath + "routes.txt") ;
			if (file.exists()) {
				FileReader fr = new FileReader(file) ;
				
				DBUtilsImpl dbUtils = new DBUtilsImpl() ;
				Connection conn = dbUtils.startConnection("jdbc:mysql://10.172.66.247:3306", "root", "grisgris123") ;
				
				GTFSDatabaseInteraction dbInt = new GTFSDatabaseInteraction() ;
				
				BufferedReader br = new BufferedReader(fr);
				String currentRecord;
				String delimiter = "," ;
				boolean flag = true;
				int result = -1, routeId = -1, agencyId = -1, routeShortName = -1, routeLongName = -1, routeDesc = -1, routeType = -1, routeUrl = -1, routeColor = -1, routeTextColor = -1 ;
				Route route = null ;
				String[] fields ;
				String field ;
				DateFormat fmt, other ;
				java.util.Date date ;
				while((currentRecord = br.readLine()) != null) {
					fields = currentRecord.split(delimiter) ;
					if (flag) {
						for (int i = 0; i < fields.length; i++) {
							field = fields[i] ;
							if (field.equals("route_id")) 
								routeId = i ;
							if (field.equals("agency_id"))
								agencyId = i ;
							if (field.equals("route_short_name"))
								routeShortName = i ;
							if (field.equals("route_long_name"))
								routeLongName = i ;
							if (field.equals("route_desc"))
								routeDesc = i ;
							if (field.equals("route_type"))
								routeType = i ;
							if (field.equals("route_url"))
								routeUrl = i ;
							if (field.equals("route_color"))
								routeColor = i ;
							if (field.equals("route_text_color"))
								routeTextColor = i ;
							flag = false ;
						}
					}
					else {
						route = new Route() ;
						for (int i = 0; i < fields.length; i++) {
							if (i == routeId) 
								route.setRouteId(fields[i]) ;
							else if (i == agencyId)
								route.setAgencyId(Integer.parseInt(fields[i])) ;
							else if (i == routeShortName)
								route.setRouteShortName(fields[i].replace("'", "''")) ;
							else if (i == routeLongName)
								route.setRouteLongName(fields[i].replace("'", "''")) ;
							else if (i == routeDesc)
								route.setRouteDesc(fields[i].replace("'", "''")) ;
							else if (i == routeType)
								route.setRouteType(Integer.parseInt(fields[i])) ;
							else if (i == routeUrl)
								route.setRouteUrl(fields[i].replace("'", "''")) ;
							else if (i == routeColor)
								route.setRouteColor(fields[i].replace("'", "''")) ;
							else if (i == routeTextColor)
								route.setRouteTextColor(fields[i].replace("'", "''")) ;
						}
						if (agencyId != -1 && routeDesc != -1 && routeUrl != -1 && routeColor != -1 && routeTextColor != -1)
							result = dbInt.insertAllFieldsRoute(conn, route) ;
						else
							result = dbInt.insertRequiredFieldsRoute(conn, route) ;
					}
				}
				conn.close() ;
				fr.close() ;
				br.close();
				return result ;
			}
			else return 1 ;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1 ;
	}

	public int parseStops(String filePath) {
		try {  
			File file = new File (filePath + "stops.txt") ;
			if (file.exists()) {
				FileReader fr = new FileReader(file) ;
				
				DBUtilsImpl dbUtils = new DBUtilsImpl() ;
				Connection conn = dbUtils.startConnection("jdbc:mysql://10.172.66.247:3306", "root", "grisgris123") ;
				
				GTFSDatabaseInteraction dbInt = new GTFSDatabaseInteraction() ;
				
				BufferedReader br = new BufferedReader(fr);
				String currentRecord;
				String delimiter = "," ;
				boolean flag = true;
				int result = -1, stopId = -1, stopCode = -1, stopName = -1, stopDesc = -1, stopLat = -1, stopLon = -1, zoneId = -1, stopUrl = -1, locationType = -1, parentStation = -1, stopTimezone = -1, wheelchairBoarding = -1 ;
				Stop stop = null ;
				String[] fields ;
				String field ;
				DateFormat fmt, other ;
				java.util.Date date ;
				while((currentRecord = br.readLine()) != null) {
					fields = currentRecord.split(delimiter) ;
					if (flag) {
						for (int i = 0; i < fields.length; i++) {
							field = fields[i] ;
							if (field.equals("stop_id")) 
								stopId = i ;
							if (field.equals("stop_code"))
								stopCode = i ;
							if (field.equals("stop_name"))
								stopName = i ;
							if (field.equals("stop_desc"))
								stopDesc = i ;
							if (field.equals("stop_lat"))
								stopLat = i ;
							if (field.equals("stop_lon"))
								stopLon = i ;
							if (field.equals("zone_id"))
								zoneId = i ;
							if (field.equals("stop_url"))
								stopUrl = i ;
							if (field.equals("location_type"))
								locationType = i ;
							if (field.equals("parent_station"))
								parentStation = i ;
							if (field.equals("stop_timezone"))
								stopTimezone = i ;
							if (field.equals("wheelchair_boarding"))
								wheelchairBoarding = i ;
							flag = false ;
						}
					}
					else {
						stop = new Stop() ;
						for (int i = 0; i < fields.length; i++) {
							if (i == stopId)
								stop.setStopId(Long.parseLong(fields[i])) ;
							if (i == stopCode)
								stop.setStopCode(fields[i].replace("'", "''")) ;
							if (i == stopName)
								stop.setStopName(fields[i].replace("'", "''")) ;
							if (i == stopDesc)
								stop.setStopDesc(fields[i].replace("'", "''")) ;
							if (i == stopLat)
								stop.setStopLat(Double.parseDouble(fields[i])) ;
							if (i == stopLon)
								stop.setStopLon(Double.parseDouble(fields[i])) ;
							if (i == zoneId)
								stop.setZoneId(Long.parseLong(fields[i])) ;
							if (i == stopUrl)
								stop.setStopUrl(fields[i].replace("'", "''")) ;
							if (i == locationType)
								stop.setLocationType(Integer.parseInt(fields[i])) ;
							if (i == parentStation)
								stop.setParentStation(Long.parseLong(fields[i])) ;
							if (i == stopTimezone)
								stop.setStopTimezone(fields[i].replace("'", "''")) ;
							if (i == wheelchairBoarding)
								stop.setWheelchairBoarding(Integer.parseInt(fields[i])) ;
						}
						if (stopCode != -1 && stopDesc != -1 && zoneId != -1 && stopUrl != -1 && locationType != -1 && parentStation != -1 && stopTimezone != -1 && wheelchairBoarding != -1)
							result = dbInt.insertAllFieldsStop(conn, stop) ;
						else
							result = dbInt.insertRequiredFieldsStop(conn, stop) ;
					}
				}
				conn.close() ;
				fr.close() ;
				br.close();
				return result ;
			}
			else return 1 ;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1 ;
	}

	public int parseTrips(String filePath, Connection conn) {
		try {  
			File file = new File (filePath + "trips.txt") ;
			if (file.exists()) {
				FileReader fr = new FileReader(file) ;
				
				GTFSDatabaseInteraction dbInt = new GTFSDatabaseInteraction() ;
				DBUtilsImpl dbUtils = new DBUtilsImpl() ;
				String selectTrips = "SELECT trip_gtfs_id FROM mobis_schema.trip" ;
				ResultSet rs = dbUtils.queryDB(conn, selectTrips) ;
				ArrayList<String> tripIds = new ArrayList<String>() ;				
				
				try {
					while (rs.next()) {
						tripIds.add(rs.getString("trip_gtfs_id")) ;
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				BufferedReader br = new BufferedReader(fr);
				String currentRecord;
				String delimiter = "," ;
				boolean flag = true;
				int result = -1, tripId = -1, tripHeadsign = -1, tripShortName = -1, directionId = -1, blockId = -1, shapeId = -1, wheelchairAccessible = -1, routeId = -1, serviceId = -1 ;
				Trip trip = null ;
				String[] fields ;
				String field ;
				DateFormat fmt, other ;
				java.util.Date date ;
				while((currentRecord = br.readLine()) != null) {
					fields = currentRecord.split(delimiter) ;
					if (flag) {
						for (int i = 0; i < fields.length; i++) {
							field = fields[i] ;
							if (field.equals("trip_id")) 
								tripId = i ;
							if (field.equals("trip_headsign"))
								tripHeadsign = i ;
							if (field.equals("trip_short_name"))
								tripShortName = i ;
							if (field.equals("direction_id"))
								directionId = i ;
							if (field.equals("block_id"))
								blockId = i ;
							if (field.equals("shape_id"))
								shapeId = i ;
							if (field.equals("wheelchair_accessible"))
								wheelchairAccessible = i ;
							if (field.equals("route_id"))
								routeId = i ;
							if (field.equals("service_id"))
								serviceId = i ;
							flag = false ;
						}
					}
					else {
						trip = new Trip() ;
						for (int i = 0; i < fields.length; i++) {
							if (i == tripId)
								trip.setTripId(fields[i].replace("'", "''")) ;
							if (i == tripHeadsign)
								trip.setTripHeadsign(fields[i].replace("'", "''")) ;
							if (i == tripShortName)
								trip.setTripShortName(fields[i].replace("'", "''")) ;
							if (i == directionId && fields[i] != "")
								trip.setDirectionId(Integer.parseInt(fields[i])) ;
							if (i == blockId)
								trip.setBlockId(fields[i].replace("'", "''")) ;
							if (i == shapeId)
								trip.setShapeId(fields[i].replace("'", "''")) ;
							if (i == wheelchairAccessible && fields[i] != "")
								trip.setWheelchairAccessible(Integer.parseInt(fields[i])) ;
							if (i == routeId)
								trip.setRouteId(fields[i].replace("'", "''")) ;
							if (i == serviceId)
								trip.setServiceId(fields[i].replace("'", "''")) ;
						}
						if (!tripIds.contains(trip.getTripId())) {
						//if (directionId != -1 && blockId != -1 && shapeId != -1 && wheelchairAccessible != -1 && tripHeadsign != -1 && tripShortName != -1)
							result = dbInt.insertAllFieldsTrip(conn, trip) ;
						//else
						//	result = dbInt.insertRequiredFieldsTrip(conn, trip) ;
						}
					}
				}
				
				fr.close() ;
				br.close();
				return result ;
			}
			else return 1 ;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1 ;
	}

	public int parseStopTimes(String filePath, Connection conn) {
		try {  
			File file = new File (filePath + "stop_times.txt") ;
			if (file.exists()) {
				FileReader fr = new FileReader(file) ;
				
				GTFSDatabaseInteraction dbInt = new GTFSDatabaseInteraction() ;
				
				DBUtilsImpl dbUtils = new DBUtilsImpl() ;
				String selectTrips = "SELECT trip_gtfs_id, stop_gtfs_id FROM mobis_schema.stop_time" ;
				ResultSet rs = dbUtils.queryDB(conn, selectTrips) ;
				ArrayList<String> tripIds = new ArrayList<String>() ;		
				ArrayList<String> stopIds = new ArrayList<String>() ;
				HashMap<String, String> tripStopIds = new HashMap<String, String>() ;
				
				try {
					while (rs.next()) {
						tripIds.add(rs.getString("trip_gtfs_id")) ;
						stopIds.add(rs.getString("stop_gtfs_id")) ;
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				BufferedReader br = new BufferedReader(fr);
				String currentRecord;
				String delimiter = "," ;
				boolean flag = true;
				int result = -1, tripId = -1, arrivalTime = -1, departureTime = -1, stopId = -1, stopSequence = -1, stopHeadsign = -1, pickupType = -1, dropOffType = -1, shapeDistTraveled = -1 ;
				StopTime stopTime = null ;
				String[] fields ;
				String field ;
				DateFormat fmt, other ;
				java.util.Date date ;
				while((currentRecord = br.readLine()) != null) {
					fields = currentRecord.split(delimiter) ;
					if (flag) {
						for (int i = 0; i < fields.length; i++) {
							field = fields[i] ;
							if (field.equals("trip_id")) 
								tripId = i ;
							if (field.equals("arrival_time"))
								arrivalTime = i ;
							if (field.equals("departure_time"))
								departureTime = i ;
							if (field.equals("stop_id"))
								stopId = i ;
							if (field.equals("stop_sequence"))
								stopSequence = i ;
							if (field.equals("stop_headsign"))
								stopHeadsign = i ;
							if (field.equals("pickup_type"))
								pickupType = i ;
							if (field.equals("drop_off_type"))
								dropOffType = i ;
							if (field.equals("shape_dist_traveled"))
								shapeDistTraveled = i ;
							flag = false ;
						}
					}
					else {
						stopTime = new StopTime() ;
						fmt = new SimpleDateFormat("HH:mm:ss") ;
						for (int i = 0; i < fields.length; i++) {
							if (i == tripId)
								stopTime.setTripId(fields[i].replace("'", "''")) ;
							if (i == arrivalTime) {
								date = fmt.parse(fields[i]) ;
								stopTime.setArrivalTime(new Timestamp(date.getTime())) ;
							}
							if (i == departureTime) {
								date = fmt.parse(fields[i]) ;
								stopTime.setDepartureTime(new Timestamp(date.getTime())) ;
							}
							if (i == stopId)
								stopTime.setStopId(fields[i].replace("'", "''")) ;
							if (i == stopSequence)
								stopTime.setStopSequence(Integer.parseInt(fields[i])) ;
							if (i == stopHeadsign)
								stopTime.setStopHeadsign(fields[i].replace("'", "''")) ;
							if (i == pickupType && !fields[i].equals(""))
								stopTime.setPickupType(Integer.parseInt(fields[i])) ;
							if (i == dropOffType && !fields[i].equals(""))
								stopTime.setDropOffType(Integer.parseInt(fields[i])) ;
							if (i == shapeDistTraveled && !fields[i].equals(""))
								stopTime.setShapeDistTraveled(Double.parseDouble(fields[i])) ;
						}
						if (tripIds.contains(stopTime.getTripId()) && stopIds.contains(stopTime.getStopId()) && stopIds.indexOf(stopTime.getStopId()) == tripIds.indexOf(stopTime.getTripId())) {
							continue ;
						}
						else {
							if (stopHeadsign != -1 && pickupType != -1 && dropOffType != -1 && shapeDistTraveled != -1)
								result = dbInt.insertAllFieldsStopTime(conn, stopTime) ;
							else
								result = dbInt.insertRequiredFieldsStopTime(conn, stopTime) ;
						}
					}
				}
				fr.close() ;
				br.close();
				return result ;
			}
			else return 1 ;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1 ;
	}

	public int parseCalendar(String filePath, Connection conn) {
		try {  
			File file = new File (filePath + "calendar.txt") ;
			if (file.exists()) {
				FileReader fr = new FileReader(file) ;
				
				GTFSDatabaseInteraction dbInt = new GTFSDatabaseInteraction() ;
				
				BufferedReader br = new BufferedReader(fr);
				String currentRecord;
				String delimiter = "," ;
				boolean flag = true;
				int result = -1, serviceId = -1, monday = -1, tuesday = -1, wednesday = -1, thursday = -1, friday = -1, saturday = -1, sunday = -1, startDate = -1, endDate = -1 ;
				Calendar calendar = null ;
				String[] fields ;
				String field ;
				DateFormat fmt, other ;
				java.util.Date date ;
				while((currentRecord = br.readLine()) != null) {
					fields = currentRecord.split(delimiter) ;
					if (flag) {
						for (int i = 0; i < fields.length; i++) {
							field = fields[i] ;
							if (field.equals("service_id")) 
								serviceId = i ;
							if (field.equals("monday"))
								monday = i ;
							if (field.equals("tuesday"))
								tuesday = i ;
							if (field.equals("wednesday"))
								wednesday = i ;
							if (field.equals("thursday"))
								thursday = i ;
							if (field.equals("friday"))
								friday = i ;
							if (field.equals("saturday"))
								saturday = i ;
							if (field.equals("sunday"))
								sunday = i ;
							if (field.equals("start_date"))
								startDate = i ;
							if (field.equals("end_date"))
								endDate = i ;
							flag = false ;
						}
					}
					else {
						calendar = new Calendar() ;
						fmt = new SimpleDateFormat("yyyyMMdd");
						other = new SimpleDateFormat("dd/MM/yyyy") ;
						
						for (int i = 0; i < fields.length; i++) {
							if (i == serviceId)
								calendar.setServiceId(fields[i].replace("'", "''")) ;
							if (i == monday)
								calendar.setMonday(Integer.parseInt(fields[i])) ;
							if (i == tuesday)
								calendar.setTuesday(Integer.parseInt(fields[i])) ;
							if (i == wednesday)
								calendar.setWednesday(Integer.parseInt(fields[i])) ;
							if (i == thursday)
								calendar.setThursday(Integer.parseInt(fields[i])) ;
							if (i == friday)
								calendar.setFriday(Integer.parseInt(fields[i])) ;
							if (i == saturday)
								calendar.setSaturday(Integer.parseInt(fields[i])) ;
							if (i == sunday)
								calendar.setSunday(Integer.parseInt(fields[i])) ;
							if (i == startDate) {
								date = fmt.parse(fields[i]) ;
								date = other.parse(other.format(date)) ;
								calendar.setStartDate(new Date(date.getTime())) ;
							}
							if (i == endDate) {
								date = fmt.parse(fields[i]) ;
								date = other.parse(other.format(date)) ;
								calendar.setEndDate(new Date(date.getTime())) ;
							}
						}
						result = dbInt.insertAllFieldsCalendar(conn, calendar) ;
					}
				}
				fr.close() ;
				br.close();
				return result ;
			}
			else return 1 ;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1 ;
	}

	public int parseCalendarDates(String filePath, Connection conn) {
		try {  
			File file = new File (filePath + "calendar_dates.txt") ;
			if (file.exists()) {
				FileReader fr = new FileReader(file) ;
				
					
				GTFSDatabaseInteraction dbInt = new GTFSDatabaseInteraction() ;
				
				BufferedReader br = new BufferedReader(fr);
				String currentRecord;
				String delimiter = "," ;
				boolean flag = true;
				int result = -1, serviceId = -1, date = -1, exceptionType = -1 ;
				CalendarDate calendarDate = null ;
				String[] fields ;
				String field ;
				DateFormat fmt, other ;
				java.util.Date dateUtil ;
				while((currentRecord = br.readLine()) != null) {
					fields = currentRecord.split(delimiter) ;
					if (flag) {
						for (int i = 0; i < fields.length; i++) {
							field = fields[i] ;
							if (field.equals("service_id")) 
								serviceId = i ;
							if (field.equals("date"))
								date = i ;
							if (field.equals("exception_type"))
								exceptionType = i ;
							flag = false ;
						}
					}
					else {
						calendarDate = new CalendarDate() ;
						fmt = new SimpleDateFormat("yyyyMMdd");
						other = new SimpleDateFormat("dd/MM/yyyy") ;
						
						for (int i = 0; i < fields.length; i++) {
							if (i == serviceId)
								calendarDate.setServiceId(fields[i].replace("'", "''")) ;
							if (i == date) {
								dateUtil = fmt.parse(fields[i]) ;
								dateUtil = other.parse(other.format(dateUtil)) ;
								calendarDate.setDate(new Date(dateUtil.getTime())) ;
							}
							if (i == exceptionType)
								calendarDate.setExceptionType(Integer.parseInt(fields[i])) ;
						}
						result = dbInt.insertAllFieldsCalendarDate(conn, calendarDate) ;
					}
				}
				fr.close() ;
				br.close();
				return result ;
			}
			else return 1 ;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1 ;
	}

	public int parseTransfers(String filePath, Connection conn) {
		try {  
			File file = new File (filePath + "transfers.txt") ;
			if (file.exists()) {
				FileReader fr = new FileReader(file) ;
				
				
				GTFSDatabaseInteraction dbInt = new GTFSDatabaseInteraction() ;
				
				BufferedReader br = new BufferedReader(fr);
				String currentRecord;
				String delimiter = "," ;
				boolean flag = true;
				int result = -1, transferType = -1, minTransferTime = -1, fromStopId = -1, toStopId = -1 ;
				Transfer transfer = null ;
				String[] fields ;
				String field ;
				DateFormat fmt, other ;
				java.util.Date date ;
				while((currentRecord = br.readLine()) != null) {
					fields = currentRecord.split(delimiter) ;
					if (flag) {
						for (int i = 0; i < fields.length; i++) {
							field = fields[i] ;
							if (field.equals("transfer_type")) 
								transferType = i ;
							if (field.equals("min_transfer_time"))
								minTransferTime = i ;
							if (field.equals("from_stop_id"))
								fromStopId = i ;
							if (field.equals("to_stop_id"))
								toStopId = i ;
							flag = false ;
						}
					}
					else {
						transfer = new Transfer() ;
						for (int i = 0; i < fields.length; i++) {
							if (i == transferType)
								transfer.setTransferType(Integer.parseInt(fields[i])) ;
							if (i == minTransferTime)
								transfer.setMinTransferTime(Integer.parseInt(fields[i])) ;
							if (i == fromStopId)
								transfer.setFromStopId(Long.parseLong(fields[i])) ;
							if (i == toStopId)
								transfer.setToStopId(Long.parseLong(fields[i])) ;
						}
						if (minTransferTime != -1)
							result = dbInt.insertAllFieldsTransfer(conn, transfer) ;
						else
							result = dbInt.insertRequiredFieldsTransfer(conn, transfer) ;
					}
				}
				fr.close() ;
				br.close();
				return result ;
			}
			else return 1 ;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1 ;
	}

	public int parseFeedInfo(String filePath, Connection conn) {
		try {  
			File file = new File (filePath + "feed_info.txt") ;
			if (file.exists()) {
				FileReader fr = new FileReader(file) ;
				
				
				GTFSDatabaseInteraction dbInt = new GTFSDatabaseInteraction() ;
				
				BufferedReader br = new BufferedReader(fr);
				String currentRecord;
				String delimiter = "," ;
				boolean flag = true;
				int result = -1, feedPublisherName = -1, feedPublisherUrl = -1, feedLang = -1, feedStartDate = -1, feedEndDate = -1, feedVersion = -1 ;
				FeedInfo feed = null ;
				String[] fields ;
				String field ;
				DateFormat fmt, other ;
				java.util.Date date ;
				while((currentRecord = br.readLine()) != null) {
					fields = currentRecord.split(delimiter) ;
					if (flag) {
						for (int i = 0; i < fields.length; i++) {
							field = fields[i] ;
							if (field.equals("feed_publisher_name")) 
								feedPublisherName = i ;
							if (field.equals("feed_publisher_url"))
								feedPublisherUrl = i ;
							if (field.equals("feed_lang"))
								feedLang = i ;
							if (field.equals("feed_start_date"))
								feedStartDate = i ;
							if (field.equals("feed_end_date"))
								feedEndDate = i ;
							if (field.equals("feed_version"))
								feedVersion = i ;
							flag = false ;
						}
					}
					else {
						feed = new FeedInfo() ;
						for (int i = 0; i < fields.length; i++) {
							if (i == feedPublisherName)
								feed.setFeedPublisherName(fields[i].replace("'", "''")) ;
							if (i == feedPublisherUrl)
								feed.setFeedPublisherUrl(fields[i].replace("'", "''")) ;
							if (i == feedLang)
								feed.setFeedLang(fields[i].replace("'", "''")) ;
							if (i == feedStartDate)
								feed.setFeedStartDate(Date.valueOf(fields[i])) ;
							if (i == feedEndDate)
								feed.setFeedEndDate(Date.valueOf(fields[i])) ;
							if (i == feedVersion)
								feed.setFeedVersion(fields[i].replace("'", "''")) ;
						}
						if (feedStartDate != -1 && feedEndDate != -1 && feedVersion != -1)
							result = dbInt.insertAllFieldsFeedInfo(conn, feed) ;
						else
							result = dbInt.insertRequiredFieldsFeedInfo(conn, feed) ;
					}
				}
				
				fr.close() ;
				br.close();
				return result ;
			}
			else return 1 ;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return -1 ;
	}

	public int parseAllGTFSFiles(String filePath, Connection conn) {
		int result = 0 ;
		//result += parseAgency(filePath) ;
		//result += parseRoutes(filePath) ;
		//result += parseStops(filePath) ;
		//result += parseCalendar(filePath) ;
		//result += parseCalendarDates(filePath) ;
		//result += parseTrips(filePath, conn) ;
		result += parseStopTimes(filePath, conn) ;
		result += parseTransfers(filePath, conn) ;
		result += parseFeedInfo(filePath, conn) ;
		if (result == 0) 
			return result ;
		else return 1 ;
	}
}
